package com.example.hm_dtfkz.ui.fragment;

import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.android.base.ui.dialog.DialogCustom;
import com.android.base.util.ActivityClickUtil;
import com.android.base.util.DQLog;
import com.android.base.util.SystemUtil;
import com.android.base.util.ToastUtil;
import com.dq.ad.AdManager;
import com.example.hm_dtfkz.R;
import com.example.hm_dtfkz.config.AppConfig;
import com.example.hm_dtfkz.config.LoginConfig;
import com.example.hm_dtfkz.databinding.FragmentDialogPushBinding;
import com.example.hm_dtfkz.entity.AdError;
import com.example.hm_dtfkz.entity.QAPermission;
import com.example.hm_dtfkz.entity.QAPushApp;
import com.example.hm_dtfkz.entity.QAPushAppExtra;
import com.example.hm_dtfkz.ui.activity.LoginActivity;
import com.example.hm_dtfkz.ui.adapter.PushAdapter;
import com.example.hm_dtfkz.ui.dialog.DialogPushExtra;
import com.example.hm_dtfkz.ui.dialog.DialogWithdrawalSuccess;
import com.example.hm_dtfkz.util.AnimUtil;
import com.example.hm_dtfkz.util.sound.MediaBackManager;
import com.hx.update.utils.DownloadUtil;
import com.hx.update.utils.HProgressDialogUtil;
import com.hx.update.utils.UpdateUtil;
import com.tencent.mm.opensdk.utils.ILog;

import java.io.File;
import java.util.List;

public class PushDialogFragment extends DialogFragment implements View.OnClickListener {

    private FragmentDialogPushBinding pushBinding;
    private PushAdapter pushAdapter;
    private QAPushAppExtra qaPushAppExtra;
    private List<QAPermission> permissionList;
    private boolean isReward;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //去掉dialog的标题，需要在setContentView()之前
        Dialog dialog = this.requireDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window window = dialog.getWindow();
        //去掉dialog默认的padding
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //设置dialog的位置在底部
        lp.gravity = Gravity.BOTTOM;
        //设置dialog的动画
        lp.windowAnimations = R.style.BottomDialogAnimation;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());

        setCancelable(false);

        pushBinding = FragmentDialogPushBinding.inflate(inflater);

        initViews();

        initData();

        initListener();

        return pushBinding.getRoot();
    }

    private void initViews() {
        // 文本框加下划线
        //pushBinding.tvRecord.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

    private void initData() {
        pushAdapter = new PushAdapter();

        pushBinding.rvTask.setAdapter(pushAdapter);
        pushBinding.ivExtraReward.setEnabled(false);
    }

    private void initListener() {
        pushBinding.tvRecord.setOnClickListener(this);
        pushBinding.ivClose.setOnClickListener(this);
        pushBinding.ivExtraReward.setOnClickListener(this);

        pushAdapter.setClickLister(new PushAdapter.OnItemChildClickLister() {
            @Override
            public void onDownload(QAPushApp item) {
//                download(item);
                showDownloadConfirm(item);
            }

            @Override
            public void onConfirm(QAPushApp item) {
                new DialogCustom(requireActivity())
                        .setMsg("是否重新下载？")
                        .setLeft("是")
                        .setRight("否")
                        .setActionLister(new DialogCustom.ActionLister() {
                            @Override
                            public void onLeftClick() {
//                                download(item);
                                showDownloadConfirm(item);
                            }

                            @Override
                            public void onRightClick() {

                            }
                        }).show();
            }

            @Override
            public void onWithdrawal(QAPushApp item, int pos) {
                if (TextUtils.isEmpty(LoginConfig.getUserOpenId())) {
                    LoginActivity.startAct(requireActivity(), LoginActivity.TYPE_BIND, null);
                } else {
                    watchVideoAd(item.getPid(), 1, item.getRa());
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getPushAppConfig();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void showDownloadConfirm(QAPushApp item) {
//        DownloadDialogFragment downloadDialogFragment = new DownloadDialogFragment();
//        downloadDialogFragment.setPushApp(item);
//        downloadDialogFragment.setPermissionList(permissionList);
//        downloadDialogFragment.setClickListener(new DownloadDialogFragment.OnClickListener() {
//            @Override
//            public void onDownload() {
//                download(item);
//            }
//        });
//        downloadDialogFragment.show(getChildFragmentManager(), "download_confirm_dialog");
    }

    private void download(QAPushApp item) {
        HProgressDialogUtil.showHorizontalProgressDialog(requireContext(), "下载进度", true);
        HProgressDialogUtil.setMax(Long.parseLong(item.getAs()));
        DownloadUtil.getInstance().download(item.getAu(), requireContext().getExternalCacheDir() + File.separator, new DownloadUtil.DownloadListener() {
            @Override
            public void onDownloadSuccess(String path) {
                // 复制互推码到剪切板
                SystemUtil.copyToClipboard(requireContext(), AppConfig.PUSH_CODE);
//                ToastUtil.showShortToastCenter(requireContext(), "下载完成:" + SystemUtil.getClipboardContent(requireContext()));
                // 发起请求，告诉服务端下载成功
//                HXCurrencySDK.getInstance().qaPushAppDownload(item.getPid(), AppConfig.PUSH_CODE, new HttpUtil.HttpUtilCallback() {
//                    @Override
//                    public void onSuccess(int i, String s) {
//                        DQLog.e("上报下载完成成功：" + s);
//                    }
//
//                    @Override
//                    public void onFailed(int i, Throwable throwable) {
//                        DQLog.e("上报下载完成失败：" + throwable.getMessage());
//                    }
//                });
                // 开始安装
                UpdateUtil.install(requireContext(), new File(path));
                HProgressDialogUtil.dismissDialog();
            }

            @Override
            public void onDownloading(long progress) {
                HProgressDialogUtil.setProgress(progress);
            }

            @Override
            public void onDownloadFailed(String err) {
                HProgressDialogUtil.dismissDialog();
                ToastUtil.showShortToastCenter(requireContext(), err);
            }
        });
    }

    private void getPushAppConfig() {
//        HXCurrencySDK.getInstance().getQaPushAppConfig(new HttpUtil.HttpUtilCallback() {
//            @Override
//            public void onSuccess(int i, String s) {
//                DQLog.e("互推配置列表：" + s);
//                QAPushAppConfigResp qaPushAppConfigResp = JsonUtil.parseObject(s, QAPushAppConfigResp.class);
//                if (qaPushAppConfigResp != null && qaPushAppConfigResp.getErrorCode() == 0) {
//                    AppConfig.PUSH_CODE = qaPushAppConfigResp.getHtm();
//                    List<QAPushApp> pal = qaPushAppConfigResp.getPal();
//                    List<QAPushAppExtra> ptl = qaPushAppConfigResp.getPtl();
//                    permissionList = qaPushAppConfigResp.getPl();
//                    updateUI(pal, ptl);
//                } else {
//                    updateUI(null, null);
//                }
//            }
//
//            @Override
//            public void onFailed(int i, Throwable throwable) {
//                DQLog.e("互推配置列表失败：" + throwable.getMessage());
//                updateUI(null, null);
//            }
//        });
    }

    private void updateUI(List<QAPushApp> list, List<QAPushAppExtra> extraList) {
        if (extraList != null) {
            int index = -1;
            int size = extraList.size();
            for (int i = 0; i < size; i++) {
                if (extraList.get(i).getZt() != 2) {
                    index = i;
                    break;
                }
            }
            if (index == -1) {
                index = size - 1;
            }
            qaPushAppExtra = extraList.get(index);
            if (qaPushAppExtra != null) {
//                DQLog.e(qaPushAppExtra.toString());
                String s = "完成<b><font color='#FD0D21'>" + qaPushAppExtra.getHts() + "</font></b>次任务可领取";
                pushBinding.tvExtraTips.setText(Html.fromHtml(s));
                double d = qaPushAppExtra.getCc() * 100 / (double) qaPushAppExtra.getHts();
                pushBinding.taskProgress.setProgress(d);
                int state = qaPushAppExtra.getZt();
                if (state == 0) {
                    AnimUtil.scaleAnim(pushBinding.ivExtraReward, 1f, 1.2f); // 小幅度动画
                } else if (state == 1) {
                    AnimUtil.scaleAnim(pushBinding.ivExtraReward, 0.9f, 1.3f); // 大幅度动画
                }
                pushBinding.ivExtraReward.setEnabled(true);

                if (index == size - 1 && state == 2) {
                    pushBinding.tvExtraTips.setText("任务已全部完成！");
                    pushBinding.taskProgress.setProgress(100);
                    pushBinding.ivExtraReward.clearAnimation(); // 清除动画
                    pushBinding.ivExtraReward.setEnabled(false);
                }
            }
        }
        if (list != null && list.size() > 0) {
            pushAdapter.setList(list);
            pushAdapter.notifyDataSetChanged();
            pushBinding.rvTask.setVisibility(View.VISIBLE);
//            pushBinding.tvEmpty.setVisibility(View.GONE);
        } else {
            pushBinding.rvTask.setVisibility(View.GONE);
//            pushBinding.tvEmpty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View view) {
        if (ActivityClickUtil.getInstance().isFastClick()) {
            //防止用户快速点击
            return;
        }
        if (view.getId() == R.id.tv_record) {
//            PushRecordActivity.startActivity(requireActivity());
        } else if (view.getId() == R.id.iv_extra_reward) {
            // 额外奖励对话框
            new DialogPushExtra(requireActivity())
                    .setCanReward(qaPushAppExtra.getZt() == 1)
                    .setClickLister(new DialogPushExtra.OnClickLister() {
                        @Override
                        public void onReceive() {
                            if (TextUtils.isEmpty(LoginConfig.getUserOpenId())) {
                                LoginActivity.startAct(requireActivity(), LoginActivity.TYPE_BIND, null);
                            } else {
                                watchVideoAd(qaPushAppExtra.getPid(), 2, qaPushAppExtra.getJl());
                            }
                        }
                    }).show();
        } else if (view.getId() == R.id.iv_close) {
            dismiss();
        }
    }

    private void watchVideoAd(final int taskId, final int type, final double rewardAmount) {
        if (AppConfig.TD_BANNED == 1) {
            ToastUtil.showShortToast(requireActivity(), AppConfig.TD_BANNED_MSG);
            return;
        }

        if (AppConfig.hasNoAd()) {
            withdrawal(taskId, type, rewardAmount);
        } else {
            isReward = false;
            if (AppConfig.getBackMusic()) {
                MediaBackManager.getInstance(requireActivity()).pause();
            }
//            AdManager.getInstance().showRewardVideoAD("", requireActivity(), new AdManager.OnRewardVideoADListener() {
//                @Override
//                public void onClosed(String orderId) {
//                    if (AppConfig.getBackMusic()) {
//                        MediaBackManager.getInstance(requireActivity()).start();
//                    }
//                    if (isReward) {
//                        withdrawal(taskId, type, rewardAmount);
//                    } else {
//                        ToastUtil.showShortToast(requireActivity(), "未完整观看视频，提现失败");
//                    }
//                }
//
//                @Override
//                public void onReward() {
//                    isReward = true;
//                }
//
//                @Override
//                public void onShow(double ecpm) {
//                }
//
//                @Override
//                public void onFailed(int i, AdError adError) {
//                    if (AppConfig.getBackMusic()) {
//                        MediaBackManager.getInstance(requireActivity()).start();
//                    }
//                    ILog.e("PushDialogFragment onFailed: " + adError.getErrorMessage());
//                    withdrawal(taskId, type, rewardAmount);
//                }
//
//                @Override
//                public void onTimeout() {
//                    if (AppConfig.getBackMusic()) {
//                        MediaBackManager.getInstance(requireActivity()).start();
//                    }
//                    ILog.e("PushDialogFragment onTimeout");
//                    withdrawal(taskId, type, rewardAmount);
//                }
//            });
        }
    }

    private void withdrawal(final int taskId, final int type, final double rewardAmount) {
        DQLog.e("互推提现开始：任务ID=" + taskId + ", type=" + type);
//        HXCurrencySDK.getInstance().qaPushAppReceive(taskId, type, new HttpUtil.HttpUtilCallback() {
//            @Override
//            public void onSuccess(int i, String s) {
//                DQLog.e("互推提现结果：" + s);
//                QAPushAppReceiveResp qaPushAppReceiveResp = JsonUtil.parseObject(s, QAPushAppReceiveResp.class);
//                if (qaPushAppReceiveResp != null) {
//                    int errorCode = qaPushAppReceiveResp.getErrorCode();
//                    String errorMessage = qaPushAppReceiveResp.getErrorMessage();
//                    if (errorCode == 0) {
//                        withdrawalSuccess(false, rewardAmount);
//                    } else if (errorCode == 10025) {
//                        new DialogWithError(requireActivity()).setType(DialogWithError.TYPE_QUEUE).show();
//                    } else if (errorCode == 10026) {
//                        withdrawalSuccess(true, rewardAmount);
//                    } else if (errorCode == 10028) {
//                        new DialogWithError(requireActivity()).show();
//                    } else {
//                        ToastUtil.showShortToastCenter(requireActivity(), errorMessage);
//                    }
//                } else {
//                    ToastUtil.showShortToastCenter(requireActivity(), "提现失败");
//                }
//            }
//
//            @Override
//            public void onFailed(int i, Throwable throwable) {
//                DQLog.e("互推提现失败：" + throwable.getMessage());
//                ToastUtil.showShortToastCenter(requireActivity(), "网络异常，提现失败");
//            }
//        });
    }

    private void withdrawalSuccess(boolean isQueue, double rat) {
        int remainWithdrawalTimes = AppConfig.getRemainWithdrawalTimes();
        if (remainWithdrawalTimes >= 1) {
            AppConfig.setRemainWithdrawalTimes(remainWithdrawalTimes - 1);
        }

        new DialogWithdrawalSuccess(requireActivity()).setCash(rat).setQueue(isQueue).setClickLister(new DialogWithdrawalSuccess.OnClickLister() {
            @Override
            public void onWithdrawal() {
                // 继续赚钱
            }
        }).show();

        getPushAppConfig();
    }
}